package com.example.presentshopping.ui.activity

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.fragment.app.FragmentActivity
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.ui.custom.PayPwdEditText
import com.example.presentshopping.ui.dialog.MessageDialog
import com.example.presentshopping.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_balance_change.*

class BalanceChangeActivity : BaseMvpActivity() {

    var telie: String? = null
    var url: String? = null
    var sendMesPresenter: PublicPresenter? = null
    private var walletDialog: Dialog? = null
    override val layoutId: Int
        get() = R.layout.activity_balance_change

    override fun initView(savedInstanceState: Bundle?) {
        sendMesPresenter = PublicPresenter(this, false, "")
        sendMesPresenter?.attachView(this)
        telie = intent?.getStringExtra("telie")
        url = intent?.getStringExtra("url")

        if(telie?.contains("兑换金币")!!){
            tex_isne.visibility =View.GONE
        }else{
            txv_isnes.text = "兑换比例   1 : 1 (最低兑换数量 ： 100 )"
            button3.setTextColor(Color.parseColor("#ffabab"))
            button3.setBackgroundColor(Color.parseColor("#ffE1E3"))
            button3.isClickable = false
            editTexnName.addTextChangedListener(object :TextWatcher{
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    //如果第一个数字为0，第二个不为点，就不允许输入
                    if (s.toString().startsWith("0") && s.toString().trim().length > 1) {
                        if (!s.toString().substring(1, 2).equals(".")) {
                            editTexnName.setText(s?.subSequence(0, 1));
                            editTexnName.setSelection(1);
                            return;
                        }
                    }
                    //如果第一为点，直接显示0.
                    if (s.toString().startsWith(".")) {
                        editTexnName.setText("8.");
                        editTexnName.setSelection(2);
                        return
                    }

                    //限制输入小数位数(2位)
                    if (s.toString().contains(".")) {
                        if (s?.length!! - 1 - s.toString().indexOf(".") > 2) {
                            var s = s.toString().subSequence(0, s.toString().indexOf(".") + 2 + 1);
                            editTexnName.setText(s);
                            editTexnName.setSelection(s.length);
                        }
                    }
                    Log.e("selected", s.toString())

                    if (!TextUtils.isEmpty(s)) {

                            if (s.toString().toDouble() < 100   ) {
                                button3.setTextColor(Color.parseColor("#ffabab"))
                                button3.setBackgroundColor(Color.parseColor("#ffE1E3"))
                                button3.isClickable = false
                            } else {
                                button3.setBackgroundColor(Color.parseColor("#FF2F5C"))
                                button3.setTextColor(Color.parseColor("#ffffff"))
                                button3.isClickable = true
                            }

                    } else {
                        button3.setTextColor(Color.parseColor("#ffabab"))
                        button3.setBackgroundColor(Color.parseColor("#ffE1E3"))
                        button3.isClickable = false
                    }
                }

                override fun afterTextChanged(s: Editable?) {


                }

            })

        }
        title_main_tv?.leftBackImageTv?.setOnClickListener { finish() }
        title_main_tv?.titleTv?.text = telie

        button3.setOnClickListener {
            if (!TextUtils.isEmpty(editTexnName.text)) {
                showEditPayPwdDialog(editTexnName.text.toString())
            } else {
                showToast("请输入兑换数量")
            }
        }



    }

    fun setBitMap(amount: String, password: String) {
        sendMesPresenter?.netWorkRequestPost( url,
            HttpRequest.getInvitationCode(amount, password))
    }


    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {
        showToast(msg)
    }

    override fun onSuccess(data: String?) {

        setDialog("兑换成功", "继续兑换")

    }

    override fun onDestroy() {
        sendMesPresenter?.detachView()
        super.onDestroy()
    }

    //平台支付
    fun showEditPayPwdDialog(order_id: String) {
        val view: View = layoutInflater.inflate(R.layout.dialog_layout, null)
        walletDialog = Dialog(this, R.style.walletFrameWindowStyle)
        walletDialog!!.setContentView(
            view, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        )

        val window = walletDialog!!.window
        val wl = window!!.attributes

        //紧贴软键盘弹出
        wl.gravity = Gravity.BOTTOM
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT
        walletDialog!!.onWindowAttributesChanged(wl)
        walletDialog!!.setCanceledOnTouchOutside(false)
        walletDialog!!.show()


        //忘记密码 按钮
        view.findViewById<View>(R.id.tv_forgetPwd).setOnClickListener {
            startActivity(
                Intent(
                    this@BalanceChangeActivity,
                    SetupPayPwdCheckActivity::class.java
                )
            )
        }
        val ppet: PayPwdEditText = view.findViewById(R.id.dialog_ppet)
        val img_cancle = view.findViewById<ImageView>(R.id.img_cancle)
        //调用initStyle方法创建你需要设置的样式
        //调用initStyle方法创建你需要设置的样式
        ppet.initStyle(R.drawable.edit_num_bg, 6, 0.33f, R.color.gray, R.color.black, 30)
        img_cancle.setOnClickListener {
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm =
                getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)

        }

        ppet.setOnTextFinishListener {
            //密码输入完后的回调
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            //可在此执行下一步操作
            val paypass = ppet.pwdText
            order_id?.let { it1 -> setBitMap(it1, paypass) }

        }
        //延迟弹起软键盘，使PayPwdEditText获取焦点
        Handler().postDelayed({ ppet.setFocus() }, 100)

    }


    fun setDialog(text: String?, Confirm: String?) {
        MessageDialog.Builder(context as FragmentActivity?)
            .setTvTitle("")
            .setTitle("")
            .setMessage(text)
            .setConfirm(Confirm)
            .setCancel("退出")
            .setListener(object : MessageDialog.OnListener {
                override fun onConfirm(dialog: Dialog?) {

                }

                override fun onCancel(dialog: Dialog?) {
                    finish()
                }

            }).show()

    }


}